/*
逻辑控制,增、删、改、查
*/
const mongoose = require("mongoose");
const User = require("../models/user.model");//引入数据模型，对用户操作

exports.get=function (req,res,next){
  const id=req.params.id;
  User.findById(id,function(err,data){
      res.json(data);
  })
}

/* 增 */
exports.create = function(req, res, next) {
  const user = new User(req.body); // 请示方式是post、添加用户
  user.save().then(data => {//返回json用户
    res.json(data);
  });
};

/* 修 */
// 参数：设参 传参 接参
exports.update = function(req, res, next) {
  // 两种不同的参数传递方式
  const id = req.params.id;//params取/id
  const user = new User(req.body);

  //new：true找到就不加，找不到就增加
  User.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    res.json(data); //返回的data是没有修改之前的数据
  });
}

/* 删 */
exports.remove = function(req, res, next) {
  const id = req.params.id;
  User.findByIdAndRemove(id, function(err, data) {
    res.json({ message: "数据已删除" });
  });
};

/* 删多个 */

exports.removes = function(req, res, next) {
  var ids = req.body.ids;
  ids=ids.split(',');
  if (ids.length > 0) {
    User.remove({ _id: { $in: ids } }).then(data => {
      res.json({ message: "多条数据已删除" });
    });
  } else {
    res.status(404).send({ message: "404" });
  }
};

/* 查 */
exports.list = function(req, res, next) {
  var page = (req.body.page) ? req.body.page : 1;
  var rows = (req.body.rows) ? req.body.rows : 5;//每页条数

  var queryCondition = {};

  if (req.body.name && req.body.name.trim().length > 0) {//确定用户是否有
    name = req.body.name;//赋值
    queryCondition = {//根据正则查询
      name: new RegExp(name, "i")
    };
  }

  User.paginate(queryCondition, { page: +page, limit: +rows }, function(err,result) {
    // res.json(result);

    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  });
};
